package com.sgb.kjwl.viewmodel.manage


import android.content.Context
import android.util.Log
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.alibaba.sdk.android.vod.upload.VODUploadCallback
import com.alibaba.sdk.android.vod.upload.VODUploadClientImpl
import com.alibaba.sdk.android.vod.upload.model.UploadFileInfo
import com.alibaba.sdk.android.vod.upload.model.VodInfo
import com.sgb.kjwl.api.APIManager
import com.sgb.kjwl.api.service.UserAPI
import com.swgk.core.view.entity.AliProofEntity
import com.sgb.kjwl.model.entity.manage.WebsiteInfoEntity
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity
import com.sgb.kjwl.view.ui.activity.manage.WebsiteUpDateOrganizationActivity
import com.swgk.core.base.BaseViewModel
import com.swgk.core.base.api.ICallBack
import com.swgk.core.base.model.entity.BaseEntity
import com.swgk.core.base.model.entity.H5ReEntity
import com.swgk.core.dialog.DialogHelper
import com.swgk.core.util.MToast
import com.swgk.core.util.PickSelectEntity
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import retrofit2.Call
import java.io.File
import kotlin.collections.set

class WebsiteUpDateOrganizationModel : BaseViewModel() {

    private var mUploadClient: VODUploadClientImpl? = null
    private var mProofEntity: AliProofEntity? = null

    val map: HashMap<String, String> = HashMap()

    val entity = ObservableField(WebsiteInfoEntity())

    val websiteInfo : MutableLiveData<WebsiteInfoEntity> = MutableLiveData()//网站信息

    val upLoadResult : MutableLiveData<String> = MutableLiveData()//上传结果

    //机构类型
    var mOrganTypes = MutableLiveData<ArrayList<PickSelectEntity<*>>>()

    //上传的视频
    val videoId = MutableLiveData<String>()



    //-----组织网站信息新增/编辑----------------------------------------------------------------
    fun setWebsiteInfo() {
        APIManager.getInstance().websiteInfoAPI.setOrganizationInfo(entity.get())
            .enqueue(object : ICallBack<BaseEntity<*>>(true, true) {
                override fun onSuccess(data: BaseEntity<*>?) {
                    if (data != null) {
                        message.postValue("编辑成功")
                    }
                }

                override fun onFailure(call: Call<BaseEntity<*>?>, t: Throwable) {
                    super.onFailure(call, t)
                }
            })
    }


    //-----网站详情----------------------------------------------------------------
    fun getWebsiteInfo(siteNo: String, siteType: Int) {
        map["siteNo"] = siteNo
        map["siteType"] = siteType.toString() + ""
        APIManager.getInstance().websiteInfoAPI.getSiteInfo(map)
            .enqueue(object : ICallBack<BaseEntity<WebsiteInfoEntity>>(true, true) {
                override fun onSuccess(data: BaseEntity<WebsiteInfoEntity>?) {
                    if (data != null) {
                        websiteInfo.postValue(data.data)
                    }
                }
            })
    }

    // -----上传相册照片---------------------------------------------------------------------------
    fun uploadAvatarFileModel(file: File?, completeNum: Int) {
        val photos: HashMap<String, RequestBody> = HashMap()
        //将文件转换成多媒体文件，方便上传
        val requestBody = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), file!!)
        photos["file" + "\"; filename=\"" + completeNum + "image.jpg\""] = requestBody
        APIManager.getInstance().uploadAPI.uploadFile(photos).enqueue(object : ICallBack<BaseEntity<*>>(true, true) {
            override fun onSuccess(data: BaseEntity<*>?) {
                if (data != null && data.data is String){
                    upLoadResult.postValue(data.data as String)
                }
            }
        })
    }

    /**
     * 获取组织机构类型
     */
    fun getOrganizationTypes(context: Context){
        val map = HashMap<String, Any>()
        map["limit"] = 20
        map["page"] = 1
        map["name"] = ""
        APIManager.getInstance().userAPI.getOrganizationTypes(UserAPI.UserCenterUrl.URL_ORGANIZATION_TYPES, map).enqueue(object :
            ICallBack<BaseEntity<List<PickSelectEntity<*>>>>(true, true) {
            override fun onSuccess(data: BaseEntity<List<PickSelectEntity<*>>>?) {
                DialogHelper.dismissProgressDialog()
                if (data != null && data.data != null){
                    mOrganTypes.postValue(data.data as ArrayList<PickSelectEntity<*>>)
                }
            }
        })
    }
    /**
     * 根据路由获取H5链接访问
     *
     * @param mContext
     * @param body     传入的参数
     * @param param    路由地址
     * @param code     返回的Code码
     */
    fun getH5Url(mContext: Context?, body: String?, param: String?, code: Int, title: String) {
        APIManager.getInstance().pickAPI.getUrlSetting(param)
            .enqueue(object : ICallBack<BaseEntity<H5ReEntity>?>(true, true) {
                override fun onSuccess(data: BaseEntity<H5ReEntity>?) {
                    if (data == null || data.state == null) {
                        return
                    }
                    if (data.state == APIManager.RESPONSE_OK) {
                        val url = data.data.url + "?title=" + title
                        WebViewX5HostActivity.start(mContext, url, body, code)
                    } else {
                        MToast.showToast(mContext, data.msg)
                    }
                }
            })
    }


    //获取视频上传凭证
    fun getVideoParamsSTS(path: String?, activity : WebsiteUpDateOrganizationActivity) {
        DialogHelper.showProgressDialog(activity, null, "视频处理中" + "...", 0, false, null)
            .setCanceledOnTouchOutside(false)
        val map: HashMap<String, Any> = HashMap()
        APIManager.getInstance().websiteInfoAPI.getVideoParams(map).enqueue(object : ICallBack<BaseEntity<AliProofEntity>>(){
            override fun onSuccess(data: BaseEntity<AliProofEntity>?) {
                if (data != null && data.data != null){
                    mProofEntity = data.data
                    val vodInfo = VodInfo()
                    vodInfo.title = ""
                    vodInfo.desc = ""
                    vodInfo.cateId = System.currentTimeMillis().toInt()
                    vodInfo.tags = null
                    if (mUploadClient == null){
                        mUploadClient = VODUploadClientImpl(activity.applicationContext)
                    }
                    mUploadClient!!.addFile(path, vodInfo)
                    //阿里凭证
                    mUploadClient!!.init(mUploadCallback)
                    mUploadClient!!.start()
                }
            }
        })
    }

    var mUploadCallback: VODUploadCallback = object : VODUploadCallback() {
        override fun onUploadSucceed(info: UploadFileInfo) {
            Log.e("onUploadSucceed", "onUploadSucceed")
            videoId.postValue(mProofEntity!!.videoId)
        }

        override fun onUploadFailed(info: UploadFileInfo, code: String, message: String) {
            Log.e("onUploadFailed", "onUploadFailed code = $code  message == $message")
        }

        override fun onUploadProgress(info: UploadFileInfo, uploadedSize: Long, totalSize: Long) {
            Log.e("onUploadFailed", "onUploadFailed")
        }

        override fun onUploadTokenExpired() {
            Log.e("onUploadTokenExpired", "onUploadTokenExpired")
            mUploadClient!!.resumeWithAuth(mProofEntity!!.uploadAuth)
        }

        override fun onUploadRetry(code: String, message: String) {
            Log.e("onUploadRetry", "onUploadRetry")
        }

        override fun onUploadRetryResume() {
            Log.e("onUploadRetryResume", "onUploadRetryResume")
        }

        override fun onUploadStarted(uploadFileInfo: UploadFileInfo) {
            Log.e("onUploadStarted", "onUploadStarted")
            mUploadClient!!.setUploadAuthAndAddress(
                uploadFileInfo,
                mProofEntity!!.uploadAuth,
                mProofEntity!!.uploadAddress
            )
        }
    }

}